import logging
import uuid
from django.db import transaction
from django.utils import timezone
from django.shortcuts import get_object_or_404
from django.db.models import Q, Avg

from rest_framework import status, viewsets, mixins, filters
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from rest_framework.decorators import action
from django_filters.rest_framework import DjangoFilterBackend
from drf_spectacular.utils import extend_schema, extend_schema_view, OpenApiExample, OpenApiParameter

from .models import Order, OrderStatusLog, OrderDocument
from .serializers import (
    OrderSerializer, OrderCreateSerializer, OrderUpdateSerializer,
    OrderStatusUpdateSerializer, OrderDocumentCreateSerializer,
    OrderListSerializer
)
from vehicle_app.models import Vehicle

logger = logging.getLogger(__name__)


@extend_schema_view(
    list=extend_schema(
        summary="获取订单列表",
        description="获取订单列表，支持按状态和支付状态筛选，支持分页。默认只返回待接单的订单",
        tags=["Orders"],
        parameters=[
            OpenApiParameter(
                name='status',
                description='订单状态，默认为待接单',
                required=False,
                type=str
            ),
            OpenApiParameter(
                name='payment_status',
                description='支付状态',
                required=False,
                type=str
            ),
            OpenApiParameter(
                name='page',
                description='页码',
                required=False,
                type=int
            ),
            OpenApiParameter(
                name='page_size',
                description='每页数量',
                required=False,
                type=int
            )
        ],
        examples=[
            OpenApiExample(
                '订单列表响应示例',
                summary='成功获取订单列表',
                description='返回订单列表数据',
                value={
                    "count": 2,
                    "next": "http://api.example.org/orders/?page=2",
                    "previous": None,
                    "results": [
                        {
                            "id": 1,
                            "order_number": "ORD20230101001",
                            "shipper_name": "13800138001",
                            "driver_name": "13800138002",
                            "vehicle_license_plate": "粤A12345",
                            "weight": "100.00单位吨",
                            "goods_type": "沥青",
                            "from_location": "广州沥青厂",
                            "to_location": "深圳工地",
                            "goods_loading_time": "2023-01-01T08:00:00Z",
                            "goods_expected_arrival_time": "2023-01-01T18:00:00Z",
                            "freight_fee": "1000.00",
                            "total_amount": "1000.00",
                            "status": "pending",
                            "status_display": "待接单",
                            "payment_status": "unpaid",
                            "payment_status_display": "未支付",
                            "expected_loading_time": "2023-01-01T08:00:00Z",
                            "expected_delivery_time": "2023-01-01T18:00:00Z",
                            "confirm_finish": False,
                            "created_at": "2023-01-01T00:00:00Z"
                        }
                    ]
                },
                response_only=True,
            )
        ]
    ),
    create=extend_schema(
        summary="创建订单",
        description="创建新订单，仅限通过认证的货主使用，直接在请求中提供订单信息。",
        tags=["Orders"],
        examples=[
            OpenApiExample(
                '创建订单请求示例',
                summary='创建订单请求',
                description='创建订单所需的请求参数。',
                value={
                    "total_price": "1000.00",
                    "deadline": "2023-01-01T18:00:00Z",
                    "shipper_notes": "货主备注",
                    "description": "订单备注",
                    "weight": "100.00单位吨",
                    "type": "沥青",
                    "from_location": "广州沥青厂",
                    "to_location": "深圳工地",
                    "goods_loading_time": "2023-01-01T08:00:00Z",
                    "goods_expected_arrival_time": "2023-01-01T18:00:00Z"
                },
                request_only=True,
            ),
            OpenApiExample(
                '创建订单响应示例',
                summary='成功创建订单',
                description='创建订单成功后的响应数据。',
                value={
                    "id": 1,
                    "order_number": "ORD20230101001",
                    "vehicle": None,
                    "shipper": {
                        "id": 2,
                        "phone": "13800138001",
                        "role": "shipper",
                        "role_display": "货主",
                        "username": "shipper1",
                        "first_name": "",
                        "last_name": "",
                        "email": "",
                        "company": "广州沥青公司",
                        "credit_score": "4.80",
                        "is_active": True,
                        "date_joined": "2023-01-01T00:00:00Z",
                        "last_login": "2023-01-01T00:00:00Z"
                    },
                    "driver": None,
                    "weight": "100.00单位吨",
                    "goods_type": "沥青",
                    "from_location": "广州沥青厂",
                    "to_location": "深圳工地",
                    "goods_loading_time": "2023-01-01T08:00:00Z",
                    "goods_expected_arrival_time": "2023-01-01T18:00:00Z",
                    "freight_fee": "1000.00",
                    "deposit": "0.00",
                    "other_fees": "0.00",
                    "total_amount": "1000.00",
                    "status": "pending",
                    "status_display": "待确认",
                    "payment_status": "unpaid",
                    "payment_status_display": "未支付",
                    "expected_loading_time": "2023-01-01T18:00:00Z",
                    "actual_loading_time": None,
                    "expected_delivery_time": "2023-01-01T18:00:00Z",
                    "actual_delivery_time": None,
                    "shipper_notes": "货主备注",
                    "driver_notes": "",
                    "confirm_finish": False,
                    "documents": [],
                    "status_logs": [
                        {
                            "id": 1,
                            "from_status": "",
                            "from_status_display": "",
                            "to_status": "pending",
                            "to_status_display": "待确认",
                            "operator": 2,
                            "operator_name": "13800138001",
                            "created_at": "2023-01-01T00:00:00Z"
                        }
                    ],
                    "created_at": "2023-01-01T00:00:00Z",
                    "updated_at": "2023-01-01T00:00:00Z"
                },
                response_only=True,
            )
        ]
    ),
    retrieve=extend_schema(
        summary="获取订单详情",
        description="根据订单ID获取订单详细信息。",
        tags=["Orders"],
        examples=[
            OpenApiExample(
                '订单详情响应示例',
                summary='成功获取订单详情',
                description='返回订单详细信息。',
                value={
                    "id": 1,
                    "order_number": "ORD20230101001",
                    "vehicle": {
                        "id": 1,
                        "user": 3,
                        "license_plate": "粤A12345",
                        "vehicle_type": "dump_truck",
                        "capacity": "20.00",
                        "status": "in_transit",
                        "status_display": "运输中",
                        "driver_name": "李四",
                        "driver_phone": "13800138002",
                        "created_at": "2023-01-01T00:00:00Z",
                        "updated_at": "2023-01-01T00:00:00Z"
                    },
                    "shipper": {
                        "id": 2,
                        "phone": "13800138001",
                        "role": "shipper",
                        "role_display": "货主",
                        "username": "shipper1",
                        "first_name": "",
                        "last_name": "",
                        "email": "",
                        "company": "广州沥青公司",
                        "credit_score": "4.80",
                        "is_active": True,
                        "date_joined": "2023-01-01T00:00:00Z",
                        "last_login": "2023-01-01T00:00:00Z"
                    },
                    "driver": {
                        "id": 3,
                        "phone": "13800138002",
                        "role": "driver",
                        "role_display": "车主",
                        "username": "driver1",
                        "first_name": "",
                        "last_name": "",
                        "email": "",
                        "company": "深圳运输公司",
                        "credit_score": "4.90",
                        "is_active": True,
                        "date_joined": "2023-01-01T00:00:00Z",
                        "last_login": "2023-01-01T00:00:00Z"
                    },
                    "weight": "100.00单位吨",
                    "goods_type": "沥青",
                    "from_location": "广州沥青厂",
                    "to_location": "深圳工地",
                    "goods_loading_time": "2023-01-01T08:00:00Z",
                    "goods_expected_arrival_time": "2023-01-01T18:00:00Z",
                    "freight_fee": "1000.00",
                    "deposit": "200.00",
                    "other_fees": "0.00",
                    "total_amount": "1000.00",
                    "status": "pending",
                    "status_display": "待确认",
                    "payment_status": "unpaid",
                    "payment_status_display": "未支付",
                    "expected_loading_time": "2023-01-01T08:00:00Z",
                    "actual_loading_time": None,
                    "expected_delivery_time": "2023-01-01T18:00:00Z",
                    "actual_delivery_time": None,
                    "shipper_notes": "请准时装货",
                    "driver_notes": "我会准时到达",
                    "confirm_finish": False,
                    "documents": [],
                    "status_logs": [
                        {
                            "id": 1,
                            "from_status": "",
                            "from_status_display": "",
                            "to_status": "pending",
                            "to_status_display": "待确认",
                            "operator": 2,
                            "operator_name": "13800138001",
                            "created_at": "2023-01-01T00:00:00Z"
                        }
                    ],
                    "created_at": "2023-01-01T00:00:00Z",
                    "updated_at": "2023-01-01T00:00:00Z"
                },
                response_only=True,
            )
        ]
    ),
)
class OrderViewSet(mixins.CreateModelMixin,
                   mixins.RetrieveModelMixin,
                   mixins.ListModelMixin,
                   viewsets.GenericViewSet):
    """订单视图集，仅使用GET和POST方法"""
    
    serializer_class = OrderSerializer
    permission_classes = [IsAuthenticated]
    pagination_class = viewsets.GenericViewSet.pagination_class  # 启用分页
    
    def get_queryset(self):
        """获取基础查询集"""
        return Order.objects.all()
    
    def get_object(self):
        """获取订单对象"""
        queryset = self.get_queryset()
        lookup_url_kwarg = self.lookup_url_kwarg or self.lookup_field
        assert lookup_url_kwarg in self.kwargs, (
            "Expected view %s to be called with a URL keyword argument "
            "named '%s'. Fix your URL conf, or set the `.lookup_field` "
            "attribute on the view correctly." % (self.__class__.__name__, lookup_url_kwarg)
        )
        filter_kwargs = {self.lookup_field: self.kwargs[lookup_url_kwarg]}
        obj = get_object_or_404(queryset, **filter_kwargs)
        return obj
    
    def get_serializer_class(self):
        """根据操作选择序列化器"""
        if self.action == 'create':
            return OrderCreateSerializer
        elif self.action == 'list':
            return OrderListSerializer
        return self.serializer_class
    
    def list(self, request):
        """获取订单列表，所有认证用户都可以访问，默认只返回待接单的订单"""
        queryset = self.get_queryset()
        
        # 默认筛选条件：只返回待接单的订单
        status = request.query_params.get('status', Order.Status.PENDING)
        payment_status = request.query_params.get('payment_status', None)
        
        if status:
            queryset = queryset.filter(status=status)
        if payment_status:
            queryset = queryset.filter(payment_status=payment_status)
            
        # 排序
        queryset = queryset.order_by('-created_at')
        
        # 分页
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)
        
        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)
    
    def create(self, request):
        """创建订单，仅限认证的货主使用"""
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        
        # 检查当前用户是否是货主
        user = request.user
        if user.role != 'shipper':
            return Response(
                {'error': '只有货主才能创建订单'},
                status=status.HTTP_403_FORBIDDEN
            )
        
        # 检查货主是否已通过认证
        if not user.role_authstatus:
            return Response(
                {'error': '只有通过认证的货主才能创建订单'},
                status=status.HTTP_403_FORBIDDEN
            )
        
        # 生成订单编号
        order_number = f"ORD{timezone.now().strftime('%Y%m%d%H%M%S')}{uuid.uuid4().hex[:6].upper()}"
        
        with transaction.atomic():
            # 创建订单（暂时不分配车辆和司机）
            order = Order.objects.create(
                order_number=order_number,
                vehicle=None,  # 暂时不分配车辆
                shipper=user,
                driver=None,   # 暂时不分配司机
                weight=serializer.validated_data.get('weight'),
                goods_type=serializer.validated_data.get('goods_type'),
                from_location=serializer.validated_data.get('from_location'),
                to_location=serializer.validated_data.get('to_location'),
                goods_loading_time=serializer.validated_data.get('goods_loading_time'),
                goods_expected_arrival_time=serializer.validated_data.get('goods_expected_arrival_time'),
                freight_fee=serializer.validated_data.get('freight_fee'),
                deposit=serializer.validated_data.get('deposit', 0),
                other_fees=serializer.validated_data.get('other_fees', 0),
                total_amount=serializer.validated_data.get('total_amount'),
                status=Order.Status.PENDING,
                payment_status=Order.PaymentStatus.UNPAID,
                expected_loading_time=serializer.validated_data.get('expected_loading_time'),
                expected_delivery_time=serializer.validated_data.get('expected_delivery_time'),
                shipper_notes=serializer.validated_data.get('shipper_notes', ''),
                driver_notes=''  # 暂时不添加司机备注
            )
            
            # 创建订单状态日志
            OrderStatusLog.objects.create(
                order=order,
                from_status='',
                to_status=order.status,
                operator=user
            )
            
            # 注意：车辆状态更新将在后续分配车辆的接口中处理
            
        serializer = OrderSerializer(order)
        return Response(
            serializer.data,
            status=status.HTTP_201_CREATED
        )
    
    def retrieve(self, request, pk=None):
        """获取订单详情，所有认证用户都可以访问"""
        order = self.get_object()
        serializer = self.get_serializer(order)
        return Response(serializer.data)
    
    @extend_schema(
        summary="更新订单信息",
        description="更新订单信息，包括运费、时间等，仅限通过认证的货主使用",
        tags=["Orders"],
        examples=[
            OpenApiExample(
                '更新订单请求示例',
                summary='更新订单请求',
                description='更新订单所需的请求参数',
                value={
                    "freight_fee": "1200.00",
                    "expected_loading_time": "2023-01-01T09:00:00Z",
                    "expected_delivery_time": "2023-01-01T19:00:00Z",
                    "shipper_notes": "请提前联系",
                    "driver_notes": "已收到通知",
                    "weight": "120.00单位吨",
                    "goods_type": "改性沥青",
                    "from_location": "广州沥青厂2号仓库",
                    "to_location": "深圳工地A区",
                    "goods_loading_time": "2023-01-01T09:00:00Z",
                    "goods_expected_arrival_time": "2023-01-01T19:00:00Z"
                },
                request_only=True,
            ),
            OpenApiExample(
                '更新订单响应示例',
                summary='成功更新订单',
                description='更新订单成功后的响应数据',
                value={
                    "id": 1,
                    "order_number": "ORD20230101001",
                    "vehicle": {
                        "id": 1,
                        "user": 3,
                        "license_plate": "粤A12345",
                        "vehicle_type": "dump_truck",
                        "capacity": "20.00",
                        "status": "in_transit",
                        "status_display": "运输中",
                        "driver_name": "李四",
                        "driver_phone": "13800138002",
                        "created_at": "2023-01-01T00:00:00Z",
                        "updated_at": "2023-01-01T00:00:00Z"
                    },
                    "shipper": {
                        "id": 2,
                        "phone": "13800138001",
                        "role": "shipper",
                        "role_display": "货主",
                        "username": "shipper1",
                        "first_name": "",
                        "last_name": "",
                        "email": "",
                        "company": "广州沥青公司",
                        "credit_score": "4.80",
                        "is_active": True,
                        "date_joined": "2023-01-01T00:00:00Z",
                        "last_login": "2023-01-01T00:00:00Z"
                    },
                    "driver": {
                        "id": 3,
                        "phone": "13800138002",
                        "role": "driver",
                        "role_display": "车主",
                        "username": "driver1",
                        "first_name": "",
                        "last_name": "",
                        "email": "",
                        "company": "深圳运输公司",
                        "credit_score": "4.90",
                        "is_active": True,
                        "date_joined": "2023-01-01T00:00:00Z",
                        "last_login": "2023-01-01T00:00:00Z"
                    },
                    "weight": "120.00单位吨",
                    "goods_type": "改性沥青",
                    "from_location": "广州沥青厂2号仓库",
                    "to_location": "深圳工地A区",
                    "goods_loading_time": "2023-01-01T09:00:00Z",
                    "goods_expected_arrival_time": "2023-01-01T19:00:00Z",
                    "freight_fee": "1200.00",
                    "deposit": "200.00",
                    "other_fees": "0.00",
                    "total_amount": "1200.00",
                    "status": "pending",
                    "status_display": "待确认",
                    "payment_status": "unpaid",
                    "payment_status_display": "未支付",
                    "expected_loading_time": "2023-01-01T09:00:00Z",
                    "actual_loading_time": None,
                    "expected_delivery_time": "2023-01-01T19:00:00Z",
                    "actual_delivery_time": None,
                    "shipper_notes": "请提前联系",
                    "driver_notes": "已收到通知",
                    "confirm_finish": False,
                    "documents": [],
                    "status_logs": [
                        {
                            "id": 1,
                            "from_status": "",
                            "from_status_display": "",
                            "to_status": "pending",
                            "to_status_display": "待确认",
                            "operator": 2,
                            "operator_name": "13800138001",
                            "created_at": "2023-01-01T00:00:00Z"
                        }
                    ],
                    "created_at": "2023-01-01T00:00:00Z",
                    "updated_at": "2023-01-01T00:00:00Z"
                },
                response_only=True,
            )
        ]
    )
    @action(detail=True, methods=['post'], url_path='update-order-info')
    def update_order_info(self, request, pk=None):
        """更新订单信息，仅限认证的货主使用"""
        order = self.get_object()
        
        # 检查当前用户是否是货主
        user = request.user
        if user != order.shipper:
            return Response(
                {'error': '只有货主才能更新订单'},
                status=status.HTTP_403_FORBIDDEN
            )
        
        # 检查货主是否已通过认证
        if not user.role_authstatus:
            return Response(
                {'error': '只有通过认证的货主才能更新订单'},
                status=status.HTTP_403_FORBIDDEN
            )
        
        serializer = OrderUpdateSerializer(order, data=request.data)
        serializer.is_valid(raise_exception=True)
        
        # 如果更新了状态，记录状态变更日志
        old_status = order.status
        new_status = serializer.validated_data.get('status', old_status)
        
        if new_status != old_status:
            # 创建订单状态日志
            OrderStatusLog.objects.create(
                order=order,
                from_status=old_status,
                to_status=new_status,
                operator=user
            )
            
            # TODO: 发送通知给相关用户
        
        serializer.save()
        return Response(serializer.data)
    
    @extend_schema(
        summary="获取我的订单",
        description="获取当前用户的订单列表，支持按角色和状态筛选",
        tags=["Orders"],
        parameters=[
            OpenApiParameter(
                name='role',
                description='用户角色 (shipper/driver)',
                required=False,
                type=str
            ),
            OpenApiParameter(
                name='status',
                description='订单状态',
                required=False,
                type=str
            )
        ],
        examples=[
            OpenApiExample(
                '我的订单列表响应示例',
                summary='成功获取我的订单列表',
                description='返回我的订单列表数据',
                value={
                    "count": 1,
                    "next": None,
                    "previous": None,
                    "results": [
                        {
                            "id": 1,
                            "order_number": "ORD20230101001",
                            "shipper_name": "13800138001",
                            "driver_name": "13800138002",
                            "vehicle_license_plate": "粤A12345",
                            "weight": "100.00单位吨",
                            "goods_type": "沥青",
                            "from_location": "广州沥青厂",
                            "to_location": "深圳工地",
                            "goods_loading_time": "2023-01-01T08:00:00Z",
                            "goods_expected_arrival_time": "2023-01-01T18:00:00Z",
                            "freight_fee": "1000.00",
                            "total_amount": "1000.00",
                            "status": "pending",
                            "status_display": "待确认",
                            "payment_status": "unpaid",
                            "payment_status_display": "未支付",
                            "expected_loading_time": "2023-01-01T08:00:00Z",
                            "expected_delivery_time": "2023-01-01T18:00:00Z",
                            "confirm_finish": False,
                            "created_at": "2023-01-01T00:00:00Z"
                        }
                    ]
                },
                response_only=True,
            )
        ]
    )
    @action(detail=False, methods=['get'], url_path='my-orders')
    def my_orders(self, request):
        """获取我的订单列表，所有认证用户都可以访问"""
        user = request.user
        role = request.query_params.get('role')
        status_param = request.query_params.get('status')
        
        if role == 'shipper':
            queryset = Order.objects.filter(shipper=user)
        elif role == 'driver':
            queryset = Order.objects.filter(driver=user)
        else:
            # 默认返回用户作为货主或车主的所有订单
            queryset = Order.objects.filter(Q(shipper=user) | Q(driver=user))
        
        # 根据状态筛选
        if status_param:
            queryset = queryset.filter(status=status_param)
        
        # 排序
        queryset = queryset.order_by('-created_at')
        
        # 分页
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = OrderListSerializer(page, many=True)
            return self.get_paginated_response(serializer.data)
        
        serializer = OrderListSerializer(queryset, many=True)
        return Response(serializer.data)
    
    @extend_schema(
        summary="更新订单状态",
        description="更新订单状态，支持完整的状态流转，仅限通过认证的货主或接单司机使用",
        tags=["Orders"],
        examples=[
            OpenApiExample(
                '更新订单状态请求示例',
                summary='更新订单状态请求',
                description='更新订单状态所需的请求参数',
                value={
                    "status": "confirmed",
                },
                request_only=True,
            ),
            OpenApiExample(
                '更新订单状态响应示例',
                summary='成功更新订单状态',
                description='更新订单状态成功后的响应数据',
                value={
                    "id": 1,
                    "order_number": "ORD20230101001",
                    "vehicle": {
                        "id": 1,
                        "user": 3,
                        "license_plate": "粤A12345",
                        "vehicle_type": "dump_truck",
                        "capacity": "20.00",
                        "status": "in_transit",
                        "status_display": "运输中",
                        "driver_name": "李四",
                        "driver_phone": "13800138002",
                        "created_at": "2023-01-01T00:00:00Z",
                        "updated_at": "2023-01-01T00:00:00Z"
                    },
                    "shipper": {
                        "id": 2,
                        "phone": "13800138001",
                        "role": "shipper",
                        "role_display": "货主",
                        "username": "shipper1",
                        "first_name": "",
                        "last_name": "",
                        "email": "",
                        "company": "广州沥青公司",
                        "credit_score": "4.80",
                        "is_active": True,
                        "date_joined": "2023-01-01T00:00:00Z",
                        "last_login": "2023-01-01T00:00:00Z"
                    },
                    "driver": {
                        "id": 3,
                        "phone": "13800138002",
                        "role": "driver",
                        "role_display": "车主",
                        "username": "driver1",
                        "first_name": "",
                        "last_name": "",
                        "email": "",
                        "company": "深圳运输公司",
                        "credit_score": "4.90",
                        "is_active": True,
                        "date_joined": "2023-01-01T00:00:00Z",
                        "last_login": "2023-01-01T00:00:00Z"
                    },
                    "weight": "100.00单位吨",
                    "goods_type": "沥青",
                    "from_location": "广州沥青厂",
                    "to_location": "深圳工地",
                    "goods_loading_time": "2023-01-01T08:00:00Z",
                    "goods_expected_arrival_time": "2023-01-01T18:00:00Z",
                    "freight_fee": "1000.00",
                    "deposit": "200.00",
                    "other_fees": "0.00",
                    "total_amount": "1000.00",
                    "status": "confirmed",
                    "status_display": "已确认",
                    "payment_status": "unpaid",
                    "payment_status_display": "未支付",
                    "expected_loading_time": "2023-01-01T08:00:00Z",
                    "actual_loading_time": "2023-01-01T08:05:00Z",
                    "expected_delivery_time": "2023-01-01T18:00:00Z",
                    "actual_delivery_time": None,
                    "shipper_notes": "请准时装货",
                    "driver_notes": "我会准时到达",
                    "confirm_finish": False,
                    "documents": [],
                    "status_logs": [
                        {
                            "id": 1,
                            "from_status": "",
                            "from_status_display": "",
                            "to_status": "pending",
                            "to_status_display": "待确认",
                            "operator": 2,
                            "operator_name": "13800138001",
                            "created_at": "2023-01-01T00:00:00Z"
                        },
                        {
                            "id": 2,
                            "from_status": "pending",
                            "from_status_display": "待确认",
                            "to_status": "confirmed",
                            "to_status_display": "已确认",
                            "operator": 3,
                            "operator_name": "13800138002",
                            "created_at": "2023-01-01T08:05:00Z"
                        }
                    ],
                    "created_at": "2023-01-01T00:00:00Z",
                    "updated_at": "2023-01-01T08:05:00Z"
                },
                response_only=True,
            )
        ]
    )
    @action(detail=True, methods=['post'], url_path='update-status')
    def update_status(self, request, pk=None):
        """更新订单状态，仅限认证的货主或接单司机使用"""
        order = self.get_object()
        
        # 检查当前用户是否是货主或接单司机
        user = request.user
        if user != order.shipper and user != order.driver:
            return Response(
                {'error': '只有货主或接单司机才能更新订单状态'},
                status=status.HTTP_403_FORBIDDEN
            )
        
        # 检查用户是否已通过认证
        if not user.role_authstatus:
            return Response(
                {'error': '只有通过认证的用户才能更新订单状态'},
                status=status.HTTP_403_FORBIDDEN
            )
        
        serializer = OrderStatusUpdateSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        
        new_status = serializer.validated_data['status']
        
        # 确定用户角色
        user_role = 'shipper' if user == order.shipper else 'driver'
        
        # 检查状态变更是否合法
        if not self._is_valid_status_transition(order.status, new_status, user_role):
            return Response(
                {'error': '非法的状态变更'},
                status=status.HTTP_400_BAD_REQUEST
            )
        
        with transaction.atomic():
            # 记录旧状态
            old_status = order.status
            
            # 更新订单状态
            order.status = new_status
            
            # 根据状态更新相关字段和时间戳
            now = timezone.now()
            if new_status == Order.Status.ACCEPTED:
                order.actual_loading_time = now
            elif new_status == Order.Status.LOADING:
                pass  # 可以添加装货开始时间
            elif new_status == Order.Status.IN_TRANSIT:
                pass  # 可以添加运输开始时间
            elif new_status == Order.Status.DELIVERED:
                order.actual_delivery_time = now
            elif new_status == Order.Status.COMPLETED:
                order.confirm_finish = True
            elif new_status == Order.Status.CANCELLED:
                pass  # 取消订单的特殊处理
            
            order.save()
            
            # 创建订单状态日志
            OrderStatusLog.objects.create(
                order=order,
                from_status=old_status,
                to_status=new_status,
                operator=user
            )
            
            # 如果订单完成或取消，更新车辆状态
            if new_status in [Order.Status.COMPLETED, Order.Status.CANCELLED]:
                # 更新车辆状态
                if order.vehicle:
                    order.vehicle.status = Vehicle.Status.AVAILABLE
                    order.vehicle.save()
            
            # 发送通知给相关用户
            self._send_order_status_notification(order, old_status, new_status, user)
            
            # 特殊状态处理
            if new_status == Order.Status.CANCELLED:
                self._send_order_cancel_notification(order.order_number, user)
            elif new_status == Order.Status.COMPLETED:
                self._send_order_complete_notification(order, user)
        
        return Response(OrderSerializer(order).data)
    
    @extend_schema(
        summary="添加订单文档",
        description="为订单添加相关文档，如装货单、送货单等，仅限通过认证的货主使用",
        tags=["Orders"],
        examples=[
            OpenApiExample(
                '添加订单文档请求示例',
                summary='添加订单文档请求',
                description='添加订单文档所需的请求参数',
                value={
                    "document_type": "delivery_receipt",
                    "document_url": "https://example.com/documents/delivery_receipt_1.pdf",
                    "description": "送货单"
                },
                request_only=True,
            ),
            OpenApiExample(
                '添加订单文档响应示例',
                summary='成功添加订单文档',
                description='添加订单文档成功后的响应数据',
                value={
                    "id": 1,
                    "document_type": "delivery_receipt",
                    "document_type_display": "送货单",
                    "document_url": "https://example.com/documents/delivery_receipt_1.pdf",
                    "description": "送货单",
                    "created_at": "2023-01-01T08:05:00Z"
                },
                response_only=True,
            )
        ]
    )
    @action(detail=True, methods=['post'], url_path='add-document')
    def add_document(self, request, pk=None):
        """添加订单文档，仅限认证的货主使用"""
        order = self.get_object()
        
        # 检查当前用户是否是货主
        user = request.user
        if user != order.shipper:
            return Response(
                {'error': '只有货主才能添加订单文档'},
                status=status.HTTP_403_FORBIDDEN
            )
        
        # 检查货主是否已通过认证
        if not user.role_authstatus:
            return Response(
                {'error': '只有通过认证的货主才能添加订单文档'},
                status=status.HTTP_403_FORBIDDEN
            )
        
        serializer = OrderDocumentCreateSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        
        # 创建订单文档
        document = OrderDocument.objects.create(
            order=order,
            document_type=serializer.validated_data['document_type'],
            document_url=serializer.validated_data['document_url'],
            description=serializer.validated_data.get('description', '')
        )
        
        return Response(
            OrderDocumentSerializer(document).data,
            status=status.HTTP_201_CREATED
        )

    @extend_schema(
        summary="取消订单",
        description="取消待确认状态的订单，仅限通过认证的货主使用，取消后订单将从数据库中删除",
        tags=["Orders"],
        examples=[
            OpenApiExample(
                '取消订单响应示例',
                summary='成功取消订单',
                description='取消订单成功后的响应数据',
                value={
                    "message": "订单已取消并删除"
                },
                response_only=True,
            )
        ]
    )
    @action(detail=True, methods=['post'], url_path='cancel-order')
    def cancel_order(self, request, pk=None):
        """取消订单，仅限认证的货主使用，取消后订单将从数据库中删除"""
        order = self.get_object()
        
        # 检查当前用户是否是货主
        user = request.user
        if user != order.shipper:
            return Response(
                {'error': '只有货主才能取消订单'},
                status=status.HTTP_403_FORBIDDEN
            )
        
        # 检查货主是否已通过认证
        if not user.role_authstatus:
            return Response(
                {'error': '只有通过认证的货主才能取消订单'},
                status=status.HTTP_403_FORBIDDEN
            )
        
        # 检查订单状态是否允许取消
        if order.status not in [Order.Status.PENDING]:
            return Response(
                {'error': '只有待确认状态的订单才能取消'},
                status=status.HTTP_400_BAD_REQUEST
            )
        
        with transaction.atomic():
            order_number = order.order_number
            
            # 删除订单相关联的数据
            # 删除订单文档
            order.documents.all().delete()
            
            # 删除订单状态日志
            order.status_logs.all().delete()
            
            # 删除订单本身
            order.delete()
        
        # 发送订单取消通知
        self._send_order_cancel_notification(order_number, user)
        
        return Response({'message': f'订单 {order_number} 已取消并删除'})
    
    @extend_schema(
        summary="司机接单",
        description="司机接单，仅限通过认证的司机使用",
        tags=["Orders"],
        request={
            'application/json': {
                'type': 'object',
                'properties': {
                    'license_plate': {
                        'type': 'string',
                        'description': '车牌号',
                        'example': '粤A12345'
                    }
                },
                'required': ['license_plate']
            }
        },
        examples=[
            OpenApiExample(
                '司机接单请求示例',
                summary='司机接单请求',
                description='司机接单时需要提供车牌号参数',
                value={
                    "license_plate": "粤A12345"
                },
                request_only=True,
            ),
            OpenApiExample(
                '司机接单响应示例',
                summary='成功接单',
                description='司机成功接单后的响应数据',
                value={
                    "id": 1,
                    "order_number": "ORD20230101001",
                    "vehicle": {
                        "id": 1,
                        "user": 3,
                        "license_plate": "粤A12345",
                        "vehicle_type": "dump_truck",
                        "capacity": "20.00",
                        "status": "in_transit",
                        "status_display": "运输中",
                        "driver_name": "李四",
                        "driver_phone": "13800138002",
                        "created_at": "2023-01-01T00:00:00Z",
                        "updated_at": "2023-01-01T08:05:00Z"
                    },
                    "shipper": {
                        "id": 2,
                        "phone": "13800138001",
                        "role": "shipper",
                        "role_display": "货主",
                        "username": "shipper1",
                        "first_name": "",
                        "last_name": "",
                        "email": "",
                        "company": "广州沥青公司",
                        "credit_score": "4.80",
                        "is_active": True,
                        "date_joined": "2023-01-01T00:00:00Z",
                        "last_login": "2023-01-01T00:00:00Z"
                    },
                    "driver": {
                        "id": 3,
                        "phone": "13800138002",
                        "role": "driver",
                        "role_display": "车主",
                        "username": "driver1",
                        "first_name": "",
                        "last_name": "",
                        "email": "",
                        "company": "深圳运输公司",
                        "credit_score": "4.90",
                        "is_active": True,
                        "date_joined": "2023-01-01T00:00:00Z",
                        "last_login": "2023-01-01T00:00:00Z"
                    },
                    "weight": "100.00单位吨",
                    "goods_type": "沥青",
                    "from_location": "广州沥青厂",
                    "to_location": "深圳工地",
                    "goods_loading_time": "2023-01-01T08:00:00Z",
                    "goods_expected_arrival_time": "2023-01-01T18:00:00Z",
                    "freight_fee": "1200.00",
                    "deposit": "0.00",
                    "other_fees": "0.00",
                    "total_amount": "1200.00",
                    "status": "in_transit",
                    "status_display": "运输中",
                    "payment_status": "unpaid",
                    "payment_status_display": "未支付",
                    "expected_loading_time": "2023-01-01T09:00:00Z",
                    "actual_loading_time": "2023-01-01T08:05:00Z",
                    "expected_delivery_time": "2023-01-01T15:00:00Z",
                    "actual_delivery_time": None,
                    "shipper_notes": "请准时到达",
                    "driver_notes": "",
                    "confirm_finish": False,
                    "documents": [],
                    "status_logs": [
                        {
                            "id": 1,
                            "from_status": "",
                            "from_status_display": "",
                            "to_status": "pending",
                            "to_status_display": "待接单",
                            "operator": 2,
                            "operator_name": "13800138001",
                            "created_at": "2023-01-01T00:00:00Z"
                        },
                        {
                            "id": 2,
                            "from_status": "pending",
                            "from_status_display": "待接单",
                            "to_status": "in_transit",
                            "to_status_display": "运输中",
                            "operator": 3,
                            "operator_name": "13800138002",
                            "created_at": "2023-01-01T08:05:00Z"
                        }
                    ],
                    "created_at": "2023-01-01T00:00:00Z",
                    "updated_at": "2023-01-01T08:05:00Z"
                },
                response_only=True,
            )
        ]
    )
    @action(detail=True, methods=['post'], url_path='accept-order')
    def accept_order(self, request, pk=None):
        """司机接单接口，需要提供车牌号参数"""
        order = self.get_object()
        user = request.user
        license_plate = request.data.get('license_plate')
        
        # 检查当前用户是否是司机
        if user.role != 'driver':
            return Response(
                {'error': '只有司机才能接单'},
                status=status.HTTP_403_FORBIDDEN
            )
        
        # 检查司机是否已通过认证
        if not user.role_authstatus:
            return Response(
                {'error': '只有通过认证的司机才能接单'},
                status=status.HTTP_403_FORBIDDEN
            )
        
        # 检查订单状态是否为待接单
        if order.status != Order.Status.PENDING:
            return Response(
                {'error': '订单状态不是待接单，无法接单'},
                status=status.HTTP_400_BAD_REQUEST
            )
        
        # 检查是否提供了车牌号
        if not license_plate:
            return Response(
                {'error': '请提供车牌号'},
                status=status.HTTP_400_BAD_REQUEST
            )
        
        # 检查司机是否拥有指定车牌号的车辆
        try:
            vehicle = user.vehicles.get(license_plate=license_plate)
        except Vehicle.DoesNotExist:
            return Response(
                {'error': f'司机没有车牌号为 {license_plate} 的车辆'},
                status=status.HTTP_400_BAD_REQUEST
            )
        
        # 检查车辆状态是否为空闲
        if vehicle.status != Vehicle.Status.AVAILABLE:
            return Response(
                {'error': f'车辆 {license_plate} 当前状态不是空闲，无法接单'},
                status=status.HTTP_400_BAD_REQUEST
            )
        
        with transaction.atomic():
            # 更新订单状态为已接单
            old_status = order.status
            order.status = Order.Status.ACCEPTED
            order.driver = user
            order.vehicle = vehicle
            order.save()
            
            # 创建订单状态日志
            OrderStatusLog.objects.create(
                order=order,
                from_status=old_status,
                to_status=order.status,
                operator=user
            )
            
            # 更新车辆状态为运输中
            vehicle.status = Vehicle.Status.IN_TRANSIT
            vehicle.save()
            
            # 发送司机接单通知
            self._send_driver_accept_order_notification(order, user)
        
        return Response(OrderSerializer(order).data)

    @extend_schema(
        summary="货主确认签收",
        description="货主确认订单签收完成，仅限通过认证的货主使用",
        tags=["Orders"],
        request=None,
        examples=[
            OpenApiExample(
                '货主确认签收响应示例',
                summary='成功确认签收',
                description='货主成功确认签收后的响应数据',
                value={
                    "id": 1,
                    "order_number": "ORD20230101001",
                    "vehicle": {
                        "id": 1,
                        "user": 3,
                        "license_plate": "粤A12345",
                        "vehicle_type": "dump_truck",
                        "capacity": "20.00",
                        "status": "completed",
                        "status_display": "已完成",
                        "driver_name": "李四",
                        "driver_phone": "13800138002",
                        "created_at": "2023-01-01T00:00:00Z",
                        "updated_at": "2023-01-01T18:05:00Z"
                    },
                    "shipper": {
                        "id": 2,
                        "phone": "13800138001",
                        "role": "shipper",
                        "role_display": "货主",
                        "username": "shipper1",
                        "first_name": "",
                        "last_name": "",
                        "email": "",
                        "company": "广州沥青公司",
                        "credit_score": "4.80",
                        "is_active": True,
                        "date_joined": "2023-01-01T00:00:00Z",
                        "last_login": "2023-01-01T00:00:00Z"
                    },
                    "driver": {
                        "id": 3,
                        "phone": "13800138002",
                        "role": "driver",
                        "role_display": "车主",
                        "username": "driver1",
                        "first_name": "",
                        "last_name": "",
                        "email": "",
                        "company": "深圳运输公司",
                        "credit_score": "4.90",
                        "is_active": True,
                        "date_joined": "2023-01-01T00:00:00Z",
                        "last_login": "2023-01-01T00:00:00Z"
                    },
                    "weight": "100.00单位吨",
                    "goods_type": "沥青",
                    "from_location": "广州沥青厂",
                    "to_location": "深圳工地",
                    "goods_loading_time": "2023-01-01T08:00:00Z",
                    "goods_expected_arrival_time": "2023-01-01T18:00:00Z",
                    "freight_fee": "1200.00",
                    "deposit": "0.00",
                    "other_fees": "0.00",
                    "total_amount": "1200.00",
                    "status": "completed",
                    "status_display": "已完成",
                    "payment_status": "unpaid",
                    "payment_status_display": "未支付",
                    "expected_loading_time": "2023-01-01T09:00:00Z",
                    "actual_loading_time": "2023-01-01T08:05:00Z",
                    "expected_delivery_time": "2023-01-01T15:00:00Z",
                    "actual_delivery_time": "2023-01-01T18:00:00Z",
                    "shipper_notes": "请准时到达",
                    "driver_notes": "货物已送达",
                    "confirm_finish": True,
                    "documents": [],
                    "status_logs": [
                        {
                            "id": 1,
                            "from_status": "",
                            "from_status_display": "",
                            "to_status": "pending",
                            "to_status_display": "待接单",
                            "operator": 2,
                            "operator_name": "13800138001",
                            "created_at": "2023-01-01T00:00:00Z"
                        },
                        {
                            "id": 2,
                            "from_status": "pending",
                            "from_status_display": "待接单",
                            "to_status": "in_transit",
                            "to_status_display": "运输中",
                            "operator": 3,
                            "operator_name": "13800138002",
                            "created_at": "2023-01-01T08:05:00Z"
                        },
                        {
                            "id": 3,
                            "from_status": "in_transit",
                            "from_status_display": "运输中",
                            "to_status": "completed",
                            "to_status_display": "已完成",
                            "operator": 3,
                            "operator_name": "13800138002",
                            "created_at": "2023-01-01T18:00:00Z"
                        },
                        {
                            "id": 4,
                            "from_status": "completed",
                            "from_status_display": "已完成",
                            "to_status": "completed",
                            "to_status_display": "已完成",
                            "operator": 2,
                            "operator_name": "13800138001",
                            "created_at": "2023-01-01T18:05:00Z"
                        }
                    ],
                    "created_at": "2023-01-01T00:00:00Z",
                    "updated_at": "2023-01-01T18:05:00Z"
                },
                response_only=True,
            )
        ],
        responses={
            200: OrderSerializer
        }
    )
    @action(detail=True, methods=['post'], url_path='confirm-finish')
    def confirm_finish(self, request, pk=None):
        """货主确认签收订单"""
        order = self.get_object()
        user = request.user
        
        # 检查当前用户是否是货主
        if user != order.shipper:
            return Response(
                {'error': '只有货主才能确认签收'},
                status=status.HTTP_403_FORBIDDEN
            )
        
        # 检查货主是否已通过认证
        if not user.role_authstatus:
            return Response(
                {'error': '只有通过认证的货主才能确认签收'},
                status=status.HTTP_403_FORBIDDEN
            )
        
        # 检查订单状态是否为已送达
        if order.status != Order.Status.DELIVERED:
            return Response(
                {'error': '只有已送达的订单才能确认签收'},
                status=status.HTTP_400_BAD_REQUEST
            )
        
        with transaction.atomic():
            # 记录旧状态
            old_status = order.status
            
            # 更新订单状态为已完成
            order.status = Order.Status.COMPLETED
            order.confirm_finish = True
            order.save()
            
            # 创建订单状态日志
            OrderStatusLog.objects.create(
                order=order,
                from_status=old_status,
                to_status=order.status,
                operator=user
            )
            
            # 更新车辆状态为空闲
            if order.vehicle:
                order.vehicle.status = Vehicle.Status.AVAILABLE
                order.vehicle.save()
            
            # 发送货主确认签收通知
            self._send_shipper_confirm_finish_notification(order, user)
            # 发送订单完成通知
            self._send_order_complete_notification(order, user)
        
        return Response(OrderSerializer(order).data)

    def _is_valid_status_transition(self, from_status, to_status, user_role):
        """检查订单状态变更是否合法"""
        # 定义有效的状态流转
        valid_transitions = {
            # 货主可以执行的操作
            'shipper': {
                Order.Status.PENDING: [Order.Status.CANCELLED],
                Order.Status.ACCEPTED: [],
                Order.Status.LOADING: [],
                Order.Status.IN_TRANSIT: [],
                Order.Status.DELIVERED: [Order.Status.COMPLETED],
                Order.Status.COMPLETED: [],
                Order.Status.CANCELLED: []
            },
            # 司机可以执行的操作
            'driver': {
                Order.Status.PENDING: [Order.Status.ACCEPTED],
                Order.Status.ACCEPTED: [Order.Status.LOADING],
                Order.Status.LOADING: [Order.Status.IN_TRANSIT],
                Order.Status.IN_TRANSIT: [Order.Status.DELIVERED],
                Order.Status.DELIVERED: [],
                Order.Status.COMPLETED: [],
                Order.Status.CANCELLED: []
            },
            # 系统自动操作
            'system': {
                Order.Status.PENDING: [Order.Status.CANCELLED],
                Order.Status.ACCEPTED: [Order.Status.CANCELLED],
                Order.Status.LOADING: [Order.Status.CANCELLED],
                Order.Status.IN_TRANSIT: [Order.Status.CANCELLED],
                Order.Status.DELIVERED: [Order.Status.CANCELLED],
                Order.Status.COMPLETED: [],
                Order.Status.CANCELLED: []
            }
        }
        
        # 根据用户角色检查状态流转是否有效
        if user_role == 'shipper':
            return to_status in valid_transitions['shipper'].get(from_status, [])
        elif user_role == 'driver':
            return to_status in valid_transitions['driver'].get(from_status, [])
        else:
            return to_status in valid_transitions['system'].get(from_status, [])
    
    def _send_order_status_notification(self, order, old_status, new_status, operator):
        """发送订单状态变更通知"""
        from notification_app.models import Notification
        
        # 通知内容模板
        status_translations = {
            Order.Status.PENDING: "待接单",
            Order.Status.IN_TRANSIT: "运输中",
            Order.Status.COMPLETED: "已完成"
        }
        
        # 为货主创建通知
        if order.shipper:
            Notification.objects.create(
                recipient=order.shipper,
                title=f"订单状态变更通知",
                content=f"您的订单 {order.order_number} 状态已从 {status_translations.get(old_status, old_status)} 变更为 {status_translations.get(new_status, new_status)}",
                notification_type=Notification.Type.ORDER,
                level=Notification.Level.INFO,
                related_order=order
            )
        
        # 为司机创建通知
        if order.driver and order.driver != order.shipper:
            Notification.objects.create(
                recipient=order.driver,
                title=f"订单状态变更通知",
                content=f"您接的订单 {order.order_number} 状态已从 {status_translations.get(old_status, old_status)} 变更为 {status_translations.get(new_status, new_status)}",
                notification_type=Notification.Type.ORDER,
                level=Notification.Level.INFO,
                related_order=order
            )
    
    def _send_driver_accept_order_notification(self, order, driver):
        """发送司机接单通知"""
        from notification_app.models import Notification
        
        # 通知货主
        if order.shipper:
            Notification.objects.create(
                recipient=order.shipper,
                title=f"司机已接单通知",
                content=f"您的订单 {order.order_number} 已被司机接单，车牌号: {order.vehicle.license_plate}",
                notification_type=Notification.Type.ORDER,
                level=Notification.Level.INFO,
                related_order=order
            )
    
    def _send_order_cancel_notification(self, order_number, operator):
        """发送订单取消通知"""
        from notification_app.models import Notification
        from user_app.models import User
        
        # 为操作员创建通知
        Notification.objects.create(
            recipient=operator,
            title=f"订单取消通知",
            content=f"您已成功取消订单 {order_number}",
            notification_type=Notification.Type.ORDER,
            level=Notification.Level.INFO
        )

    def _send_shipper_confirm_finish_notification(self, order, shipper):
        """发送货主确认签收通知"""
        from notification_app.models import Notification
        
        # 通知司机
        if order.driver:
            Notification.objects.create(
                recipient=order.driver,
                title=f"货主确认签收通知",
                content=f"订单 {order.order_number} 已被货主确认签收，订单已完成",
                notification_type=Notification.Type.ORDER,
                level=Notification.Level.SUCCESS,
                related_order=order
            )

    def _send_order_complete_notification(self, order, operator):
        """发送订单完成通知"""
        from notification_app.models import Notification
        
        # 通知货主
        if order.shipper:
            Notification.objects.create(
                recipient=order.shipper,
                title=f"订单已完成通知",
                content=f"您的订单 {order.order_number} 已送达，请检查后确认签收！",
                notification_type=Notification.Type.ORDER,
                level=Notification.Level.SUCCESS,
                related_order=order
            )
        
        # 通知司机
        if order.driver and order.driver != order.shipper:
            Notification.objects.create(
                recipient=order.driver,
                title=f"订单已完成通知",
                content=f"您运输的订单 {order.order_number} 已完成，费用将尽快结算！",
                notification_type=Notification.Type.ORDER,
                level=Notification.Level.SUCCESS,
                related_order=order
            )
